const multer = require('multer')
const path = require('path')
const { upload_config }  = require('../config/upload')

// 定义上传目录
const goodsUploadDir = upload_config.upload_images
const editorUploadDir = upload_config.upload_ueditor

//定义上传类型
const mimes_type = ['.png','.gif', '.jpg', '.jpeg']
//  {
//     '.png': 'image/png',
//     '.gif': 'image/gif',
//     '.jpg': 'image/jpeg',
//     '.jpeg': 'image/jpeg',
//     '.zip':'application/zip'
//     //后续可添加 pdf, excel, word等
// }

// 定义multer磁盘存储配置
const storageGoods  = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, goodsUploadDir)
    },
    //获取文件MD5，重命名，添加后缀,文件重复会直接覆盖
    filename: function(req, file, cb) {
        const {name, ext }  = path.parse(file.originalname)
        cb(null, `${name}${ext}`)
    }
})

const storageEditor  = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, editorUploadDir)
    },
    //获取文件MD5，重命名，添加后缀,文件重复会直接覆盖
    filename: function(req, file, cb) {
        const {name, ext }  = path.parse(file.originalname)
        cb(null, `${name}${ext}`)
    }
})

// 定义过滤器
const fileFilter = function (req, file, cb) {
    const test = mimes_type.includes(path.parse(file.originalname).ext)
    if (test) {
        cb(null, true)
    } else {
        cb('上传文件类型不合法', false)
    }
}

// 定义文件上传大小现值
const file_limit = {
    fileSize: 1024 * 1024 * 2 // 2MB
}

const multerGoodsConfig = multer({
    storage: storageGoods,
    fileFilter: fileFilter,
    limits: file_limit
})

const multerEditorConfig = multer({
    storage: storageEditor,
    fileFilter: fileFilter,
    limits: file_limit
})

module.exports = {
    multerGoodsConfig,
    multerEditorConfig
}

